package cn.edu.tju.elm.service.impl;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.dto.wallet.WalletOperationDto;
import cn.edu.tju.elm.dto.wallet.WalletDto;
import cn.edu.tju.elm.dto.wallet.WalletRuleDto;
import cn.edu.tju.elm.dto.wallet.WalletTransactionDto;
import cn.edu.tju.elm.model.wallet.Wallet;
import cn.edu.tju.elm.model.wallet.WalletRule;
import cn.edu.tju.elm.model.wallet.WalletTransaction;
import cn.edu.tju.elm.repository.wallet.WalletRepository;
import cn.edu.tju.elm.repository.wallet.WalletRuleRepository;
import cn.edu.tju.elm.repository.wallet.WalletTransactionRepository;
import cn.edu.tju.elm.service.domain.VirtualWallet;
import cn.edu.tju.elm.service.WalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class WalletServiceImpl implements WalletService {
        
    @Autowired
    private WalletRepository walletRepository;
    
    @Autowired
    private WalletRuleRepository walletRuleRepository;
    
    @Autowired
    private WalletTransactionRepository walletTransactionRepository;
    
    // ========== 钱包管理 ==========
    
    @Override
    public WalletDto createWallet(Long userId, User creator) {
        if (walletRepository.existsByUserId(userId)) {
            throw new IllegalArgumentException("用户已存在钱包");
        }
        
        Wallet wallet = new Wallet();
        wallet.setUserId(userId);
        wallet.setBalance(BigDecimal.ZERO);
        wallet.setFrozenAmount(BigDecimal.ZERO);
        wallet.setIncomingFrozenAmount(BigDecimal.ZERO);
        // 默认为普通用户，透支额度1000元
        wallet.setMembershipLevel(cn.edu.tju.elm.model.wallet.MembershipLevel.REGULAR);
        wallet.setOverdraftLimit(cn.edu.tju.elm.model.wallet.MembershipLevel.REGULAR.getOverdraftLimit());
        wallet.setRewardAmount(BigDecimal.ZERO);
        LocalDateTime now = LocalDateTime.now();
        wallet.setCreateTime(now);
        wallet.setUpdateTime(now);
        wallet.setCreator(creator.getId());
        wallet.setUpdater(creator.getId());
        wallet.setDeleted(false);
        
        Wallet savedWallet = walletRepository.save(wallet);
        return convertToWalletDto(new VirtualWallet(savedWallet));
    }
    
    @Override
    public WalletDto getWalletByUserId(Long userId) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(userId);
        return convertToWalletDto(virtualWallet);
    }
    
    @Override
    public boolean existsByUserId(Long userId) {
        return walletRepository.existsByUserId(userId);
    }
    
    @Override
    public VirtualWallet getWalletDomainByUserId(Long userId) {
        Wallet wallet = walletRepository.findByUserId(userId)
            .orElseThrow(() -> new IllegalArgumentException("用户钱包不存在"));
        return new VirtualWallet(wallet);
    }
    
    @Override
    public WalletDto purchaseSvip(Long userId, Long operator) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(userId);
        Wallet wallet = virtualWallet.getWallet();
        
        // SVIP价格19.99元
        BigDecimal svipPrice = new BigDecimal("19.99");
        
        // 检查是否已经是有效的SVIP
        if (wallet.isActiveSvip()) {
            throw new IllegalStateException("您已经是SVIP用户，无需重复购买");
        }
        
        // 检查余额是否足够（不允许透支购买会员）
        if (!virtualWallet.hasSufficientBalance(svipPrice)) {
            throw new IllegalArgumentException("余额不足，无法购买SVIP，请先充值");
        }
        
        // 扣除费用（不使用透支）
        virtualWallet.pay(svipPrice, false);
        
        // 设置SVIP状态（30天有效期）
        wallet.setMembershipLevel(cn.edu.tju.elm.model.wallet.MembershipLevel.SVIP);
        wallet.setMembershipExpireTime(LocalDateTime.now().plusDays(30));
        
        // 更新透支额度为SVIP级别（3000元）
        wallet.setOverdraftLimit(cn.edu.tju.elm.model.wallet.MembershipLevel.SVIP.getOverdraftLimit());
        
        // 保存状态
        saveWalletState(virtualWallet, operator);
        
        // 记录购买SVIP交易
        createTransaction(
            virtualWallet.getId(), null, svipPrice.negate(), "PAYMENT", "SUCCESS",
            BigDecimal.ZERO, BigDecimal.ZERO, null, null,
            "购买SVIP会员（30天）",
            operator
        );
        
        return convertToWalletDto(virtualWallet);
    }
    
    // ========== 资金操作 ==========
    
    @Override
    public WalletTransactionDto recharge(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 计算奖励金额（所有用户统一10%）
        BigDecimal rewardAmount = calculateRechargeReward(operationDto.getAmount());
        
        // 调用Domain对象的业务方法（会自动归还透支）
        BigDecimal repayAmount = virtualWallet.recharge(operationDto.getAmount(), rewardAmount);
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        // 如果有透支还款，先记录还款交易
        if (repayAmount.compareTo(BigDecimal.ZERO) > 0) {
            createTransaction(
                null, virtualWallet.getId(), repayAmount, "OVERDRAFT_REPAYMENT", "SUCCESS",
                BigDecimal.ZERO, BigDecimal.ZERO, null, null,
                "充值自动归还透支 " + repayAmount + "元",
                operationDto.getOperator()
            );
        }
        
        // 记录充值交易流水
        WalletTransaction transaction = createTransaction(
            null, virtualWallet.getId(), 
            operationDto.getAmount().add(rewardAmount), "DEPOSIT", "SUCCESS",
            BigDecimal.ZERO, rewardAmount, null, operationDto.getBusinessId(),
            buildRemark("充值", operationDto.getAmount(), rewardAmount, null, operationDto.getRemark()),
            operationDto.getOperator()
        );
        
        return convertToTransactionDto(transaction);
    }
    
    @Override
    public WalletTransactionDto withdraw(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 计算手续费
        BigDecimal feeAmount = calculateWithdrawFee(operationDto.getAmount());
        
        // 确保手续费不为null，如果为null则设为0
        if (feeAmount == null) {
            feeAmount = BigDecimal.ZERO;
        }
        
        // 验证手续费计算是否正确
        // 如果手续费为0，可能是规则不存在，需要检查
        if (feeAmount.compareTo(BigDecimal.ZERO) == 0) {
            // 重新查询规则，确保规则存在
            List<WalletRule> withdrawRules = walletRuleRepository.findByRuleTypeAndIsActiveTrue("WITHDRAW");
            if (!withdrawRules.isEmpty()) {
                WalletRule rule = withdrawRules.get(0);
                if (rule != null && rule.getRuleValue() != null) {
                    // 重新计算手续费
                    feeAmount = operationDto.getAmount().multiply(rule.getRuleValue());
                }
            }
        }
        
        // 调用Domain对象的业务方法（会扣除提现金额+手续费）
        // withdraw方法会计算 totalDeduct = amount + fee，然后从钱包中扣除
        virtualWallet.withdraw(operationDto.getAmount(), feeAmount);
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        // 记录交易流水
        // totalAmount = -(提现金额 + 手续费)，负数表示扣减
        BigDecimal totalAmount = operationDto.getAmount().add(feeAmount).negate();
        WalletTransaction transaction = createTransaction(
            virtualWallet.getId(), null, totalAmount, "WITHDRAW", "SUCCESS",
            feeAmount, BigDecimal.ZERO, null, operationDto.getBusinessId(),
            buildRemark("提现", operationDto.getAmount(), null, feeAmount, operationDto.getRemark()),
            operationDto.getOperator()
        );
        
        return convertToTransactionDto(transaction);
    }
    
    @Override
    public WalletTransactionDto pay(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 获取是否允许透支（默认允许）
        boolean allowOverdraft = operationDto.getAllowOverdraft();
        
        // 调用Domain对象的业务方法（支持透支支付）
        BigDecimal overdraftUsed = virtualWallet.pay(operationDto.getAmount(), allowOverdraft);
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        // 根据是否使用透支，记录不同类型的交易
        WalletTransaction transaction;
        if (overdraftUsed.compareTo(BigDecimal.ZERO) > 0) {
            // 使用了透支，记录为透支支付交易
            BigDecimal normalPayment = operationDto.getAmount().subtract(overdraftUsed);
            String remark = operationDto.getRemark();
            if (normalPayment.compareTo(BigDecimal.ZERO) > 0) {
                // 部分余额 + 部分透支
                remark = String.format("%s (余额支付: ¥%.2f, 透支支付: ¥%.2f)", 
                    operationDto.getRemark(), normalPayment, overdraftUsed);
            } else {
                // 完全透支支付
                remark = operationDto.getRemark() + " (透支支付)";
            }
            
            transaction = createTransaction(
                virtualWallet.getId(), null, operationDto.getAmount().negate(), "OVERDRAFT_PAY", "SUCCESS",
                BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), null,
                remark, operationDto.getOperator()
            );
        } else {
            // 未使用透支，记录为普通支付交易
            transaction = createTransaction(
                virtualWallet.getId(), null, operationDto.getAmount().negate(), "PAYMENT", "SUCCESS",
                BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), null,
                operationDto.getRemark(), operationDto.getOperator()
            );
        }
        
        return convertToTransactionDto(transaction);
    }
    
    @Override
    public List<WalletTransactionDto> transfer(WalletOperationDto operationDto) {
        VirtualWallet fromWallet = getWalletDomainByUserId(operationDto.getUserId());
        VirtualWallet toWallet = getWalletDomainByUserId(operationDto.getTargetUserId());
        
        // 调用Domain对象的业务方法
        fromWallet.transferTo(toWallet, operationDto.getAmount());
        
        // 保存两个钱包状态
        saveWalletState(fromWallet, operationDto.getOperator());
        saveWalletState(toWallet, operationDto.getOperator());
        
        // 创建两条交易记录
        WalletTransaction fromTransaction = createTransaction(
            fromWallet.getId(), toWallet.getId(), operationDto.getAmount().negate(), "TRANSFER_OUT", "SUCCESS",
            BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), null,
            operationDto.getRemark(), operationDto.getOperator()
        );
        
        WalletTransaction toTransaction = createTransaction(
            fromWallet.getId(), toWallet.getId(), operationDto.getAmount(), "TRANSFER_IN", "SUCCESS",
            BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), null,
            operationDto.getRemark(), operationDto.getOperator()
        );
        
        return List.of(
            convertToTransactionDto(fromTransaction),
            convertToTransactionDto(toTransaction)
        );
    }
    
    @Override
    public WalletTransactionDto refund(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 调用Domain对象的业务方法（会自动归还透支）
        BigDecimal repayAmount = virtualWallet.refund(operationDto.getAmount(), 
                           operationDto.getIncludeFrozen() != null ? operationDto.getIncludeFrozen() : false);
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        // 如果有透支还款，先记录还款交易
        if (repayAmount.compareTo(BigDecimal.ZERO) > 0) {
            createTransaction(
                null, virtualWallet.getId(), repayAmount, "OVERDRAFT_REPAYMENT", "SUCCESS",
                BigDecimal.ZERO, BigDecimal.ZERO, null, null,
                "退款自动归还透支 " + repayAmount + "元",
                operationDto.getOperator()
            );
        }
        
        // 记录退款交易流水
        WalletTransaction transaction = createTransaction(
            null, virtualWallet.getId(), operationDto.getAmount(), "REFUND", "SUCCESS",
            BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), null,
            operationDto.getRemark(), operationDto.getOperator()
        );
        
        return convertToTransactionDto(transaction);
    }
    
    @Override
    public WalletTransactionDto freeze(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 调用Domain对象的业务方法
        virtualWallet.freeze(operationDto.getAmount());
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        WalletTransaction transaction = createTransaction(
            virtualWallet.getId(), null, operationDto.getAmount().negate(), "FREEZE", "SUCCESS",
            BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), null,
            operationDto.getRemark(), operationDto.getOperator()
        );
        
        return convertToTransactionDto(transaction);
    }
    
    @Override
    public WalletTransactionDto unfreeze(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 调用Domain对象的业务方法
        virtualWallet.unfreeze(operationDto.getAmount());
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        WalletTransaction transaction = createTransaction(
            null, virtualWallet.getId(), operationDto.getAmount(), "UNFREEZE", "SUCCESS",
            BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), null,
            operationDto.getRemark(), operationDto.getOperator()
        );
        
        return convertToTransactionDto(transaction);
    }

    @Override
    public WalletTransactionDto freezeIncome(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        virtualWallet.freezeIncome(operationDto.getAmount());
        saveWalletState(virtualWallet, operationDto.getOperator());
        WalletTransaction transaction = createTransaction(
            null, virtualWallet.getId(), BigDecimal.ZERO, "FREEZE_INCOME", "SUCCESS",
            BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), operationDto.getBusinessId(),
            buildRemark("入账冻结", operationDto.getAmount(), null, null, operationDto.getRemark()),
            operationDto.getOperator()
        );
        return convertToTransactionDto(transaction);
    }

    @Override
    public WalletTransactionDto realizeIncomeToFrozen(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        virtualWallet.realizeIncomeToFrozen(operationDto.getAmount());
        saveWalletState(virtualWallet, operationDto.getOperator());
        WalletTransaction transaction = createTransaction(
            null, virtualWallet.getId(), operationDto.getAmount(), "REALIZE_INCOME", "SUCCESS",
            BigDecimal.ZERO, BigDecimal.ZERO, operationDto.getOrderId(), operationDto.getBusinessId(),
            buildRemark("支付完成转为冻结", operationDto.getAmount(), null, null, operationDto.getRemark()),
            operationDto.getOperator()
        );
        return convertToTransactionDto(transaction);
    }
    
    // ========== 透支管理 ==========
    
    @Override
    public WalletDto setOverdraftLimit(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 调用Domain对象的业务方法
        virtualWallet.setOverdraftLimit(operationDto.getAmount());
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        return convertToWalletDto(virtualWallet);
    }
    
    @Override
    public WalletDto increaseOverdraftLimit(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 调用Domain对象的业务方法
        virtualWallet.increaseOverdraftLimit(operationDto.getAmount());
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        return convertToWalletDto(virtualWallet);
    }
    
    @Override
    public WalletDto decreaseOverdraftLimit(WalletOperationDto operationDto) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(operationDto.getUserId());
        
        // 调用Domain对象的业务方法
        virtualWallet.decreaseOverdraftLimit(operationDto.getAmount());
        
        // 保存状态
        saveWalletState(virtualWallet, operationDto.getOperator());
        
        return convertToWalletDto(virtualWallet);
    }
    
    // ========== 查询服务 ==========
    
    @Override
    public Page<WalletTransactionDto> getTransactions(Long userId, Pageable pageable) {
        Wallet wallet = walletRepository.findByUserId(userId)
            .orElseThrow(() -> new IllegalArgumentException("用户钱包不存在"));
        
        Page<WalletTransaction> transactions = walletTransactionRepository.findByWalletId(wallet.getId(), pageable);
        return transactions.map(this::convertToTransactionDto);
    }
    
    @Override
    public List<WalletTransactionDto> getTransactionsByPeriod(Long userId, Date startDate, Date endDate) {
        Wallet wallet = walletRepository.findByUserId(userId)
            .orElseThrow(() -> new IllegalArgumentException("用户钱包不存在"));
        
        List<WalletTransaction> transactions = walletTransactionRepository
            .findByCreateTimeBetweenAndWalletId(startDate, endDate, wallet.getId());
        
        return transactions.stream()
            .map(this::convertToTransactionDto)
            .collect(Collectors.toList());
    }
    
    @Override
    public boolean hasSufficientBalance(Long userId, BigDecimal amount) {
        VirtualWallet virtualWallet = getWalletDomainByUserId(userId);
        return virtualWallet.hasSufficientBalance(amount);
    }
    
    // ========== 规则管理 ==========
    
    @Override
    public WalletRuleDto createRewardRule(WalletRuleDto ruleDto, Long operator) {
        WalletRule rule = new WalletRule();
        rule.setRuleType(ruleDto.getRuleType());
        rule.setRuleName(ruleDto.getRuleName());
        rule.setConditionValue(ruleDto.getConditionValue());
        rule.setRuleValue(ruleDto.getRuleValue());
        rule.setIsActive(ruleDto.getIsActive());
        
        LocalDateTime now = LocalDateTime.now();
        rule.setCreateTime(now);
        rule.setUpdateTime(now);
        rule.setCreator(operator);
        rule.setUpdater(operator);
        rule.setDeleted(false);
        
        WalletRule savedRule = walletRuleRepository.save(rule);
        return convertToRuleDto(savedRule);
    }
    
    @Override
    public WalletRuleDto enableRule(Long ruleId, Long operator) {
        WalletRule rule = walletRuleRepository.findById(ruleId)
            .orElseThrow(() -> new IllegalArgumentException("规则不存在"));
        
        rule.setIsActive(true);
        rule.setUpdateTime(LocalDateTime.now());
        rule.setUpdater(operator);
        
        WalletRule updatedRule = walletRuleRepository.save(rule);
        return convertToRuleDto(updatedRule);
    }
    
    @Override
    public WalletRuleDto disableRule(Long ruleId, Long operator) {
        WalletRule rule = walletRuleRepository.findById(ruleId)
            .orElseThrow(() -> new IllegalArgumentException("规则不存在"));
        
        rule.setIsActive(false);
        rule.setUpdateTime(LocalDateTime.now());
        rule.setUpdater(operator);
        
        WalletRule updatedRule = walletRuleRepository.save(rule);
        return convertToRuleDto(updatedRule);
    }
    
    @Override
    public List<WalletRuleDto> getActiveRules() {
        List<WalletRule> rules = walletRuleRepository.findByIsActiveTrue();
        return rules.stream()
            .map(this::convertToRuleDto)
            .collect(Collectors.toList());
    }
    
    @Override
    public List<WalletRuleDto> getApplicableDepositRules(BigDecimal amount) {
        List<WalletRule> rules = walletRuleRepository.findApplicableDepositRules(amount);
        return rules.stream()
            .map(this::convertToRuleDto)
            .collect(Collectors.toList());
    }
    
    // ========== 私有辅助方法 ==========
    
    private void saveWalletState(VirtualWallet virtualWallet, Long operator) {
        Wallet wallet = virtualWallet.getWallet();
        LocalDateTime now = LocalDateTime.now();
        wallet.setUpdateTime(now);
        wallet.setUpdater(operator);
        walletRepository.save(wallet);
    }
    
    private WalletTransaction createTransaction(Long fromWalletId, Long toWalletId, 
                                              BigDecimal amount, String type, String status,
                                              BigDecimal fee, BigDecimal rewardAmount, 
                                              Long orderId, Long businessId, String remark, 
                                              Long operator) {
        WalletTransaction transaction = new WalletTransaction();
        transaction.setAmount(amount);
        transaction.setType(type);
        transaction.setFromWalletId(fromWalletId);
        transaction.setToWalletId(toWalletId);
        transaction.setStatus(status);
        transaction.setFee(fee);
        transaction.setRewardAmount(rewardAmount);
        transaction.setOrderId(orderId);
        transaction.setBusinessId(businessId);
        transaction.setRemark(remark);
        transaction.setTransactionNo(generateTransactionNo());
        LocalDateTime now = LocalDateTime.now();
        transaction.setCreateTime(now);
        transaction.setUpdateTime(now);
        transaction.setCreator(operator);
        transaction.setUpdater(operator);
        transaction.setDeleted(false);
        
        return walletTransactionRepository.save(transaction);
    }
    
    private String generateTransactionNo() {
        return "T" + System.currentTimeMillis() + 
               UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }
    
    private BigDecimal calculateRechargeReward(BigDecimal amount) {
        List<WalletRule> rules = walletRuleRepository.findApplicableDepositRules(amount);
        if (rules.isEmpty()) {
            return BigDecimal.ZERO;
        }
        WalletRule bestRule = rules.get(0);
        
        // 检查规则是否匹配（充值金额 >= 条件值）
        if (bestRule.getConditionValue().compareTo(amount) <= 0) {
            // 按照"每充值100元赠送10元"的规则计算
            // 计算可以赠送多少个奖励单位（每conditionValue元一个）
            BigDecimal multiplier = amount.divide(bestRule.getConditionValue(), 0, java.math.RoundingMode.DOWN);
            // 奖励金额 = 倍数 * 每个单位的奖励值
            return multiplier.multiply(bestRule.getRuleValue());
        }
        return BigDecimal.ZERO;
    }
    
    /**
     * 根据用户会员级别计算充值奖励（考虑SVIP加成）
     */
    private BigDecimal calculateRechargeRewardWithMembership(BigDecimal amount, VirtualWallet virtualWallet) {
        // 如果是有效的SVIP用户，应用SVIP奖励率（20%）
        if (virtualWallet.getWallet().isActiveSvip()) {
            // SVIP用户：充值金额 * 20%
            return amount.multiply(new BigDecimal("0.20"));
        }
        
        // 普通用户：使用基础规则或默认10%
        BigDecimal baseReward = calculateRechargeReward(amount);
        if (baseReward.compareTo(BigDecimal.ZERO) > 0) {
            return baseReward;
        }
        
        // 如果没有配置规则，普通用户默认10%
        return amount.multiply(new BigDecimal("0.10"));
    }
    
    private BigDecimal calculateWithdrawFee(BigDecimal amount) {
        // 查询所有激活的提现规则
        List<WalletRule> rules = walletRuleRepository.findByRuleTypeAndIsActiveTrue("WITHDRAW");
        if (rules == null || rules.isEmpty()) {
            // 如果没有找到规则，返回0手续费
            return BigDecimal.ZERO;
        }
        
        // 获取第一个规则（通常只有一个提现手续费规则）
        WalletRule rule = rules.get(0);
        if (rule == null || rule.getRuleValue() == null) {
            return BigDecimal.ZERO;
        }
        
        // 计算手续费：提现金额 × 手续费率
        // 例如：提现100元，手续费率0.1（10%），手续费 = 100 × 0.1 = 10元
        BigDecimal fee = amount.multiply(rule.getRuleValue());
        
        // 确保手续费不为负数
        if (fee.compareTo(BigDecimal.ZERO) < 0) {
            return BigDecimal.ZERO;
        }
        
        return fee;
    }
    
    private String buildRemark(String action, BigDecimal amount, BigDecimal reward, 
                             BigDecimal fee, String customRemark) {
        StringBuilder sb = new StringBuilder(action);
        sb.append(": ").append(amount);
        if (reward != null && reward.compareTo(BigDecimal.ZERO) > 0) {
            sb.append(", 奖励: ").append(reward);
        }
        if (fee != null && fee.compareTo(BigDecimal.ZERO) > 0) {
            sb.append(", 手续费: ").append(fee);
        }
        if (customRemark != null && !customRemark.trim().isEmpty()) {
            sb.append(" - ").append(customRemark);
        }
        return sb.toString();
    }
    
    // ========== DTO转换方法 ==========
    
    private WalletDto convertToWalletDto(VirtualWallet virtualWallet) {
        WalletDto dto = new WalletDto();
        dto.setId(virtualWallet.getId());
        dto.setUserId(virtualWallet.getUserId());
        dto.setBalance(virtualWallet.getBalance());
        dto.setFrozenAmount(virtualWallet.getFrozenAmount());
        dto.setAvailableBalance(virtualWallet.getAvailableBalance());
        dto.setOverdraftLimit(virtualWallet.getOverdraftLimit());
        dto.setRewardAmount(virtualWallet.getRewardAmount());
        dto.setUserOverdraft(virtualWallet.getUsedOverdraft());
        dto.setStatus(virtualWallet.isOverdraft() ? "OVERDRAFT" : "NORMAL");
        dto.setIncomingFrozenAmount(virtualWallet.getWallet().getIncomingFrozenAmount());
        // 添加会员信息
        dto.setMembershipLevel(virtualWallet.getWallet().getMembershipLevel().name());
        dto.setMembershipExpireTime(virtualWallet.getWallet().getMembershipExpireTime());
        dto.setIsActiveSvip(virtualWallet.getWallet().isActiveSvip());
        return dto;
    }
    
    private WalletTransactionDto convertToTransactionDto(WalletTransaction transaction) {
        WalletTransactionDto dto = new WalletTransactionDto();
        dto.setId(transaction.getId());
        dto.setAmount(transaction.getAmount());
        dto.setType(transaction.getType());
        dto.setToWalletId(transaction.getToWalletId());
        dto.setFromWalletId(transaction.getFromWalletId());
        dto.setStatus(transaction.getStatus());
        dto.setFee(transaction.getFee());
        dto.setRewardAmount(transaction.getRewardAmount());
        dto.setOrderId(transaction.getOrderId());
        dto.setBusinessId(transaction.getBusinessId());
        dto.setRemark(transaction.getRemark());
        dto.setTransactionNo(transaction.getTransactionNo());
        dto.setCreateTime(transaction.getCreateTime());
        dto.setUpdateTime(transaction.getUpdateTime());
        return dto;
    }
    
    private WalletRuleDto convertToRuleDto(WalletRule rule) {
        WalletRuleDto dto = new WalletRuleDto();
        dto.setId(rule.getId());
        dto.setRuleType(rule.getRuleType());
        dto.setRuleName(rule.getRuleName());
        dto.setConditionValue(rule.getConditionValue());
        dto.setRuleValue(rule.getRuleValue());
        dto.setIsActive(rule.getIsActive());
        return dto;
    }
}
